package com.glwan.fixedassetapp.helper;

import static android.content.Context.AUDIO_SERVICE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Spinner;

import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.handler.ReaderResponseInterfaces;
import com.glwan.fixedassetapp.model.RFIDTagData;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.rscja.barcode.BarcodeDecoder;
import com.rscja.barcode.BarcodeFactory;
import com.rscja.deviceapi.RFIDWithUHFUART;
import com.rscja.deviceapi.entity.Gen2Entity;
import com.rscja.deviceapi.entity.UHFTAGInfo;
import com.rscja.deviceapi.interfaces.IUHFInventoryCallback;
import com.zebra.rfid.api3.ReaderDevice;

import java.util.ArrayList;
import java.util.HashMap;

public class ChainWayReaderHelper implements RFIDDeviceInterface {

    private static final String TAG = "CHAINWAY";

    private static ChainWayReaderHelper chainWayHelper;
    private static ArrayList<ReaderDevice> availableRFIDReaderList;
    public RFIDWithUHFUART mReader;
    public boolean loopFlag = false;
    Spinner spSessionID, spInventoried;
    BarcodeDecoder barcodeDecoder = BarcodeFactory.getInstance().getBarcodeDecoder();
    HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();
    // 是否已经连接
    private boolean isConnected = false;
    private boolean isConnectUHF = false;
    private boolean inventoryStatus = false;
    // 0--inventory 1--locate
    private int inventoryMode = 0;
    // tagPattern
    private String tagPattern;
    // 播放提示音
    private AudioManager am;
    private float volumnRatio;
    private SoundPool soundPool;
    private Activity activity;

    public static ChainWayReaderHelper getInstance(Activity activity) {
        if (chainWayHelper == null) {
            chainWayHelper = new ChainWayReaderHelper();
        }
        chainWayHelper.activity = activity;
        return chainWayHelper;
    }

    // 初始化音频
    private void initSound() {
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        soundMap.put(1, soundPool.load(this.activity, R.raw.barcodebeep, 1));
        soundMap.put(2, soundPool.load(this.activity, R.raw.serror, 1));
        am = (AudioManager) this.activity.getSystemService(AUDIO_SERVICE);// 实例化AudioManager对象
    }

    private void releaseSoundPool() {
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
        }
    }

    @Override
    public boolean connect() {
        Log.d(TAG, "InitSDK");
        initUHF();
        initSound();
        return true;
    }    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                UHFTAGInfo info = (UHFTAGInfo) msg.obj;
                Log.i(TAG, "UHFReadTagFragment.info=" + info);
                String rssi = info.getRssi();
                String ant = info.getAnt();
                String tid = info.getTid();
                String epc = info.getEPC();
                String user = info.getUser();
                // System.out.println("------------------------------------读取数据开始---------------------------------------");
                // System.out.println("tid:" + tid);
                // System.out.println("epc:" + epc);
                // System.out.println("user:" + user);
                // System.out.println("------------------------------------读取数据结束---------------------------------------");
                Log.i(TAG, "UHFReadTagFragment.tid=" + tid + " epc=" + epc + " user=" + user);
                RFIDTagData rfidTagData = new RFIDTagData();
                // rfidTagData.setRssi(Integer.parseInt(rssi));
                rfidTagData.setEpc(epc);
                rfidTagData.setAntennaID(Short.parseShort(ant));
                addDataToList(rfidTagData);
            } else if (msg.what == 2) {
                if (loopFlag) {
                    handler.sendEmptyMessageDelayed(2, 10);
                    // setTotalTime();
                } else {
                    handler.removeMessages(2);
                }
            }
        }
    };

    @Override
    public boolean disconnect() {
        Log.d(TAG, "disconnect " + mReader);
        releaseSoundPool();
        if (mReader != null) {
            // 关闭下电
            isConnectUHF = mReader.free();
            if (isConnectUHF) {
                CommonUtil.toastShow(activity, String.valueOf(mReader.getConnectStatus()), CommonUtil.SUCCESS, true);
            } else {
                CommonUtil.toastShow(activity, String.valueOf(mReader.getConnectStatus()), CommonUtil.ERROR, true);
            }
        }
        return !isConnectUHF;
    }

    @Override
    public boolean startInventory() {
        if (!inventoryStatus) {     // 识别标签
            mReader.setInventoryCallback(new IUHFInventoryCallback() {
                @Override
                public void callback(UHFTAGInfo uhftagInfo) {
                    Message msg = handler.obtainMessage();
                    msg.obj = uhftagInfo;
                    msg.what = 1;
                    handler.sendMessage(msg);
                    playSound(1);
                }
            });
            if (mReader.startInventoryTag()) {
                loopFlag = true;
                // time = System.currentTimeMillis();
                handler.sendEmptyMessageDelayed(2, 10);
            } else {
                stopInventory();
                CommonUtil.toastShow(activity, "盘读失败！", CommonUtil.ERROR, true);
            }
        } else {
            stopInventory();
            CommonUtil.toastShow(activity, "停止盘读", CommonUtil.SUCCESS, true);
        }
        return false;
    }

    /**
     * 添加数据到列表中
     *
     * @param
     */
    private void addData(String epc) {
        playSound(1);
    }

    /**
     * 播放提示音
     *
     * @param id 成功1，失败2
     */
    public void playSound(int id) {
        float audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); // 返回当前AudioManager对象的最大音量值
        float audioCurrentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);// 返回当前AudioManager对象的音量值
        volumnRatio = audioCurrentVolume / audioMaxVolume;
        try {
            soundPool.play(soundMap.get(id), volumnRatio, // 左声道音量
                    volumnRatio, // 右声道音量
                    1, // 优先级，0为最低
                    0, // 循环次数，0不循环，-1永远循环
                    1 // 回放速度 ，该值在0.5-2.0之间，1为正常速度
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean stopInventory() {
        Log.d(TAG, "停止盘读");
        if (loopFlag) {
            loopFlag = false;
            if (!mReader.stopInventory()) {
                CommonUtil.toastShow(activity, "停止盘读失败！", CommonUtil.SUCCESS, true);
            }
        }
        return loopFlag;
    }

    @Override
    public boolean setPower(int power) {
        Log.d(TAG, "设置功率:" + power);
        boolean flag = mReader.setPower(power);
        return flag;
    }

    @Override
    public Integer getPower() {
        Log.d(TAG, "获取功率");
        int power = mReader.getPower();
        return power;
    }

    @Override
    public boolean setSession(int session) {
        int seesionid = spSessionID.getSelectedItemPosition();
        int inventoried = spInventoried.getSelectedItemPosition();
        if (seesionid < 0 || inventoried < 0) {
            return false;
        }
        Gen2Entity p = mReader.getGen2();
        if (p != null) {
            p.setQueryTarget(inventoried);
            p.setQuerySession(seesionid);
            if (mReader.setGen2(p)) {
                CommonUtil.toastShow(activity, "设置成功", CommonUtil.SUCCESS, true);
            } else {
                CommonUtil.toastShow(activity, "设置失败", CommonUtil.ERROR, true);
            }
        } else {
            CommonUtil.toastShow(activity, "设置失败", CommonUtil.ERROR, true);
        }
        return false;
    }

    @Override
    public Integer getSession() {
        int session = 0;
        Gen2Entity p = mReader.getGen2();
        if (p != null) {
            spSessionID.setSelection(p.getQuerySession());
            spInventoried.setSelection(p.getQueryTarget());
            return session;
        }
        return session;
    }

    @Override
    public boolean isConnected() {
        return isConnectUHF;
    }

    @Override
    public void changeInventoryMode(int mode, String tagPattern) {
    }

    public void initUHF() {
        Log.d(TAG, "初始化UHF");
        try {
            mReader = RFIDWithUHFUART.getInstance();
        } catch (Exception ex) {
            CommonUtil.toastShow(activity, activity.getString(R.string.connectFail) + mReader.getConnectStatus(), CommonUtil.ERROR, true);
            return;
        }
        if (mReader != null) {
            new InitTask().execute();
        }
    }

    /**
     * 添加数据到列表中
     *
     * @param
     */
    private void addDataToList(RFIDTagData rfidTagData) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                activity.runOnUiThread(() -> {
                    if (activity instanceof
                            ReaderResponseInterfaces.ResponseTagHandler) {
                        ((ReaderResponseInterfaces.ResponseTagHandler) activity).handleResponse(rfidTagData);
                        // editText.append(stringBuilder.toString());
                    }
                });
                return null;
            }
        }.execute();
    }

    public class InitTask extends AsyncTask<String, Integer, Boolean> {
        ProgressDialog mypDialog;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            return mReader.init();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            mypDialog.cancel();
            if (!result) {
                // Toast.makeText(BaseTabFragmentActivity.this, "init fail", Toast.LENGTH_SHORT).show();
                CommonUtil.toastShow(activity, "init fail", CommonUtil.ERROR, true);
            }
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            mypDialog = new ProgressDialog(activity);
            mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mypDialog.setMessage("init...");
            mypDialog.setCanceledOnTouchOutside(false);
            mypDialog.show();
        }
    }



}
